import React, { useEffect, useState } from "react";
import Taro, { getCurrentInstance, useDidShow } from "@tarojs/taro";
import { AtImagePicker, AtInput } from "taro-ui";
import { View, RadioGroup, Radio } from "@tarojs/components";

import Label from "@cmp/label/index.jsx";
import { uploadImgs } from "@util/util";
import api from "@api/api.js";
import "./index.less";
import doctorPng from "@assets/plan/doctor.jpg";

export default () => {
  const [id, setId] = useState(""); // 案例id
  const [dtl, setDtl] = useState({}); // 案例详情
  const [sysParam, setSysParam] = useState({ case_data_type: [] }); // 数据字典
  const [page, setPage] = useState(false);
  useEffect(() => {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    prevPage.route == "pages/myCase/index" && setPage(true);
    getSysParam();
    const paramId = getCurrentInstance().router.params.id;
    if (paramId) {
      setId(paramId);
      getEditCase({ caseId: paramId });
    } else {
      Taro.setTopBarText("新建案例");
    }
  }, []);
  // 数据字典
  const getSysParam = async () => {
    const { data } = await api.getSysParam(["case_data_type"]);
    setSysParam(data);
  };
  // 获取案例详情
  const getEditCase = async (param) => {
    const { data } = await api.getEditCase(param);
    // 图片回显
    const res = data.afterImg.map((item) => ({
      url: api.bseUrl + item.path,
      id: item.id,
    }));
    const resX = data.beforeImg.map((item) => ({
      url: api.bseUrl + item.path,
      id: item.id,
    }));
    data.afterImg = res;
    data.beforeImg = resX;
    setDtl({ ...data });
  };
  // 监听输入框改变
  const change = (key, value) => {
    setDtl({ ...dtl, [key]: value });
  };
  // 监听单选改变
  const radioChange = (key, value) => {
    setDtl({ ...dtl, [key]: value.detail.value });
  };
  // 删除材料
  const deleteMt = async (paramId) => {
    const { code } = await api.deleteCaseSubject({
      caseId: id,
      subjectId: paramId,
    });
    if (code == 200) {
      getEditCase({ caseId: id });
      Taro.showToast({
        title: "材料删除成功",
        icon: "none",
      });
    }
  };
  // 图片上传
  const uploadImg = (type, file) => {
    dtl[type] = file;
    setDtl({ ...dtl });
  };
  // 保存
  const saveCase = async () => {
    const { afterImg, beforeImg } = dtl;
    const [afterImgIds, beforeImgIds] = await Promise.all([
      uploadImgs(afterImg),
      uploadImgs(beforeImg),
    ]);
    const { code, errorMessage } = await api.saveCase({
      ...dtl,
      afterImgIds,
      beforeImgIds,
    });
    if (code == 200) {
      page
        ? Taro.navigateBack({ delta: 1 })
        : Taro.navigateTo({ url: `/pages/myCase/index` });
    } else {
      Taro.showToast({
        title: errorMessage,
        icon: "none",
      });
    }
  };
  return (
    <View className="bgBox">
      <View className="listBox">
        <View className="dtl borderBottom">
          <View className="title">
            {dtl.clinic}
            <View className="fontBlue">编辑分类</View>
          </View>
          <View>
            <View className="fontBold">{dtl.operation}</View>
            <View className="operationList">
              <Label
                list={dtl.materials}
                onDelete={(id) => {
                  deleteMt(id);
                }}
              />
            </View>
          </View>
        </View>
        <View className="uploadImg at-row at-row__justify--between borderBottom">
          <View className="at-col at-col-5">
            <View className="uploadTitle">术前</View>
            <AtImagePicker
              length={1}
              files={dtl.beforeImg}
              onChange={uploadImg.bind(this, "beforeImg")}
            />
          </View>
          <View className="at-col at-col-5">
            <View className="uploadTitle">术后</View>
            <AtImagePicker
              length={1}
              files={dtl.afterImg}
              onChange={uploadImg.bind(this, "afterImg")}
            />
          </View>
        </View>
        <View className="remarks borderBottom">
          <View className="fontBold">备注</View>
          <AtInput
            value={dtl.remark}
            placeholder="请输入备注内容"
            placeholderClass="font"
            onChange={change.bind(this, "remark")}
          />
        </View>
        <View className="myRadio clearFloat">
          <View className="radioLable">
            <RadioGroup onChange={radioChange.bind(this, "caseType")}>
              {sysParam.case_data_type.map((item) => {
                return (
                  <Radio
                    value={item.paramCode}
                    checked={item.paramCode == dtl.caseType}
                  >
                    {item.paramDesc}
                  </Radio>
                );
              })}
            </RadioGroup>
          </View>
          <View className="fontBold">选择权限</View>
        </View>
      </View>
      <View className="bottomBtn" onClick={saveCase}>
        <View>确认编辑</View>
      </View>
    </View>
  );
};
